package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext ctx;

    @Override
    public void deleteByPrimaryKey(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Permission selectByPrimaryKey(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public void load() {
        List<String> resource = permissionMapper.selectAllResource();

        Map<String, Object> beans = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> values = beans.values();
        for (Object obj : values) {
            Method[] ms = obj.getClass().getSuperclass().getDeclaredMethods();
            Method[] declaredMethods = ms;
            for (Method m : declaredMethods) {
                RequiresPermissions anno = m.getAnnotation(RequiresPermissions.class);
                if (anno != null) {
                    String[] value = anno.value();

                    if (!resource.contains(value[0])) {
                        Permission permission = new Permission();
                        permission.setName(value[1]);
                        permission.setResource(value[0]);
                        permissionMapper.insert(permission);
                    }
                }
            }
        }

    }


    @Override
    public PageResult query(QueryObject qo) {
        int total = permissionMapper.query4Count(qo);
        if (total == 0) {
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<?> rows = permissionMapper.query4List(qo);
        return new PageResult(total, rows);
    }

    @Override
    public List<Permission> selectPermissionByRoleId(Long id) {
        return permissionMapper.selectPermissionByRoleId(id);
    }
}
